package utils

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"log"
	"os"
	"reflect"
	"strconv"
	"strings"
)

func GetUUID() string {
	u, err := uuid.NewRandom()
	if err != nil {
		log.Println(err)
	}
	return u.String()
}

func IsDirectory(path string) bool {
	fi, err := os.Stat(path)
	if err != nil {
		return false
	}
	return fi.IsDir()
}

func CheckNil(value interface{}) bool {
	if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
		return true
	}
	return false
}

func IsBlank(value reflect.Value) bool {
	switch value.Kind() {
	case reflect.String:
		return value.Len() == 0
	case reflect.Bool:
		return !value.Bool()
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return value.Int() == 0
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return value.Uint() == 0
	case reflect.Float32, reflect.Float64:
		return value.Float() == 0
	case reflect.Interface, reflect.Ptr:
		return value.IsNil()
	}
	return reflect.DeepEqual(value.Interface(), reflect.Zero(value.Type()).Interface())
}

// 计算分页页码
func CalculatePage(total, size int) int {
	if size == 0 {
		return 0
	}
	return (total + size - 1) / size
}

func String2Int(val string) int {
	i, _ := strconv.Atoi(val)
	return i
}

func Int2String(a int) string {
	str := strconv.Itoa(a)
	return str
}

func SplitStringChar(s string) []string {
	a := strings.FieldsFunc(s, func(r rune) bool {
		return r == ','
	})
	return a
}

func GetClientIP(c *gin.Context) string {
	ClientIP := c.ClientIP()
	fmt.Println("ClientIP:", ClientIP)
	RemoteIP, _ := c.RemoteIP()
	fmt.Println("RemoteIP:", RemoteIP)
	ip := c.Request.Header.Get("X-Forwarded-For")
	if strings.Contains(ip, "127.0.0.1") || ip == "" {
		ip = c.Request.Header.Get("X-real-ip")
	}
	if ip == "" {
		ip = "127.0.0.1"
	}
	if RemoteIP.String() != "127.0.0.1" {
		ip = RemoteIP.String()
	}
	if ClientIP != "127.0.0.1" {
		ip = ClientIP
	}
	return ip
}
